<template>
  <div class="activity-list">
    <div class="page-header">
      <div class="header-title">
        <h2>活动列表</h2>
        <span class="subtitle">管理所有社团活动</span>
      </div>
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-plus" @click="handleAddActivity">添加活动</el-button>
      </div>
    </div>

    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="活动名称">
          <el-input v-model="filterForm.title" placeholder="请输入活动名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="举办地点">
          <el-input v-model="filterForm.location" placeholder="请输入地点" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="未开始" value="未开始"></el-option>
            <el-option label="进行中" value="进行中"></el-option>
            <el-option label="已结束" value="已结束"></el-option>
            <el-option label="已取消" value="已取消"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <div class="table-operations">
        <el-button-group>
          <el-button size="small" @click="handleBatchExport">导出数据</el-button>
          <el-button size="small" @click="handleRefresh">刷新</el-button>
        </el-button-group>
      </div>
      
      <el-table
        :data="activityList"
        style="width: 100%"
        border
        v-loading="loading"
        @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" ></el-table-column> -->
        <el-table-column prop="title" label="活动名称" >
          <template slot-scope="scope">
            <el-link type="primary" @click="viewActivityDetail(scope.row)">{{ scope.row.title }}</el-link>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="club" label="举办社团" ></el-table-column> -->
        <el-table-column prop="tags" label="活动类型">
          <template slot-scope="scope">
            <template v-if="scope.row.tags">
              <el-tag 
                v-for="(tag, index) in scope.row.tags.split(',')" 
                :key="index"
                :type="getTagType(tag.trim())"
                style="margin-right: 5px; margin-bottom: 5px;">
                {{ tag.trim() }}
              </el-tag>
            </template>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="活动地点" ></el-table-column>
        <el-table-column prop="createTime" label="开始时间">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-tag :type="getStatusTypeByValue(scope.row.status)">
              {{ getStatusTextByValue(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="viewActivityDetail(scope.row)">查看</el-button>
            <el-button 
              type="text" 
              size="small" 
              :class="{ 'danger-button': scope.row.status !== 2 }"
              @click="cancelActivity(scope.row)"
              v-if="scope.row.status === 0 || scope.row.status === 1">
              撤销活动
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 活动详情对话框 -->
    <el-dialog title="活动详情" :visible.sync="activityDetailVisible" width="70%">
      <div v-if="currentActivity" class="activity-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="活动名称">{{ currentActivity.title }}</el-descriptions-item>
          <el-descriptions-item label="组织者">{{ currentActivity.organizer }}</el-descriptions-item>
          <el-descriptions-item label="最大参与人数">{{ currentActivity.maxParticipants }}</el-descriptions-item>
          <el-descriptions-item label="活动地点">{{ currentActivity.location }}</el-descriptions-item>
          <el-descriptions-item label="活动日期">{{ formatDate(currentActivity.date) }}</el-descriptions-item>
          <el-descriptions-item label="活动时间">{{ currentActivity.time }}</el-descriptions-item>
          <el-descriptions-item label="活动类型">
            <template v-if="currentActivity.tags">
              <el-tag 
                v-for="(tag, index) in currentActivity.tags.split(',')" 
                :key="index"
                :type="getTagType(tag.trim())"
                style="margin-right: 5px; margin-bottom: 5px;">
                {{ tag.trim() }}
              </el-tag>
            </template>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTypeByValue(currentActivity.status)">
              {{ getStatusTextByValue(currentActivity.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="活动简介" :span="2">{{ currentActivity.description }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-section">
          <h3>活动图片</h3>
          <div class="activity-image-container">
            <el-image 
              v-if="currentActivity.image" 
              :src="currentActivity.image" 
              fit="cover"
              style="width: 100%; max-width: 500px; border-radius: 4px;">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
            <div v-else class="no-image">
              <i class="el-icon-picture-outline"></i>
              <span>暂无图片</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 编辑活动对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="activityForm" :rules="activityRules" ref="activityForm" label-width="100px">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="activityForm.name"></el-input>
        </el-form-item>
        <el-form-item label="举办社团" prop="club">
          <el-input v-model="activityForm.club"></el-input>
        </el-form-item>
        <el-form-item label="活动类型" prop="type">
          <el-select v-model="activityForm.type" placeholder="请选择类型" style="width: 100%">
            <el-option label="文化活动" value="文化活动"></el-option>
            <el-option label="体育赛事" value="体育赛事"></el-option>
            <el-option label="学术讲座" value="学术讲座"></el-option>
            <el-option label="志愿服务" value="志愿服务"></el-option>
            <el-option label="招新活动" value="招新活动"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="activityForm.location"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="activityForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="activityForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动简介" prop="description">
          <el-input type="textarea" v-model="activityForm.description" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="activityForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="未开始" value="未开始"></el-option>
            <el-option label="进行中" value="进行中"></el-option>
            <el-option label="已结束" value="已结束"></el-option>
            <el-option label="已取消" value="已取消"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitActivityForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import httpInstance from "@/utils/http";

export default {
  name: 'ActivityList',
  data() {
    return {
      loading: false,
      filterForm: {
        title: '',
        location: '',
        status: ''
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      activityList: [],
      selectedActivities: [],
      activityDetailVisible: false,
      currentActivity: null,
      editDialogVisible: false,
      dialogTitle: '添加活动',
      activityForm: {
        id: null,
        name: '',
        club: '',
        type: '',
        location: '',
        startTime: '',
        endTime: '',
        description: '',
        status: '未开始'
      },
      activityRules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        club: [
          { required: true, message: '请输入举办社团', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择活动类型', trigger: 'change' }
        ],
        location: [
          { required: true, message: '请输入活动地点', trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入活动简介', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      // 模拟数据
      activitySchedules: [
        { content: '签到入场', time: '14:00-14:30', type: 'primary' },
        { content: '开场致辞', time: '14:30-14:45', type: 'success' },
        { content: '主题活动', time: '14:45-16:30', type: 'warning' },
        { content: '颁奖仪式', time: '16:30-17:00', type: 'danger' },
        { content: '合影留念', time: '17:00-17:15', type: 'info' }
      ],
      activityPhotos: [
        { url: 'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg' },
        { url: 'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg' },
        { url: 'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg' },
        { url: 'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg' }
      ],
      allActivities: []
    }
  },
  created() {
    // 检查token是否存在
    const token = localStorage.getItem('token')
    if (!token) {
      this.$router.push('/admin/login')
    }
    
    this.fetchActivityList();
  },
  methods: {
    // 获取活动列表
    async fetchActivityList() {
      this.loading = true;
      try {
        // 实际API调用，获取所有数据
        const response = await httpInstance.post('/api/activity/list', this.filterForm);
        console.log("获取活动的数据", response);
        if (response && response.code === 200) {
          // 保存所有数据
          this.allActivities = response.data || [];
          
          // 设置总条数
          this.pagination.total = this.allActivities.length;
          
          // 执行前端分页
          this.handleFrontendPagination();
        } else {
          this.$message.error(response?.msg || '获取活动列表失败');
        }
      } catch (error) {
        console.error('获取活动列表失败:', error);
        this.$message.error('获取活动列表失败，请稍后重试');
      } finally {
        this.loading = false;
      }
    },
    
    // 新增前端分页方法
    handleFrontendPagination() {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize;
      const end = start + this.pagination.pageSize;
      // 从所有数据中截取当前页需要显示的数据
      this.activityList = this.allActivities.slice(start, end);
    },
    
    // 查询
    handleSearch() {
      // 先通过本地过滤筛选数据
      if (this.filterForm.title || this.filterForm.location || this.filterForm.status) {
        this.allActivities = this.allActivities.filter(item => {
          let matchTitle = true, matchLocation = true, matchStatus = true;
          
          if (this.filterForm.title) {
            matchTitle = item.title && item.title.includes(this.filterForm.title);
          }
          
          if (this.filterForm.location) {
            matchLocation = item.location && item.location.includes(this.filterForm.location);
          }
          
          if (this.filterForm.status) {
            matchStatus = item.status === this.filterForm.status;
          }
          
          return matchTitle && matchLocation && matchStatus;
        });
        
        this.pagination.total = this.allActivities.length;
      } else {
        // 如果没有筛选条件，重新获取所有数据
        this.fetchActivityList();
        return;
      }
      
      // 重置到第一页并执行分页
      this.pagination.currentPage = 1;
      this.handleFrontendPagination();
    },
    
    // 重置表单
    resetForm() {
      this.filterForm = {
        name: '',
        club: '',
        type: '',
        status: ''
      };
      this.handleSearch();
    },
    
    // 刷新
    handleRefresh() {
      this.fetchActivityList();
    },
    
    // 导出数据
    handleBatchExport() {
      this.$message.success('导出成功，文件已下载');
    },
    
    // 表格选择项变化
    handleSelectionChange(selection) {
      this.selectedActivities = selection;
    },
    
    // 查看活动详情
    viewActivityDetail(activity) {
      this.currentActivity = activity;
      this.activityDetailVisible = true;
    },
    
    // 编辑活动
    editActivity(activity) {
      this.dialogTitle = '编辑活动';
      this.activityForm = { ...activity };
      this.editDialogVisible = true;
    },
    
    // 添加活动
    handleAddActivity() {
      this.dialogTitle = '添加活动';
      this.activityForm = {
        id: null,
        name: '',
        club: '',
        type: '',
        location: '',
        startTime: '',
        endTime: '',
        description: '',
        status: '未开始'
      };
      this.editDialogVisible = true;
    },
    
    // 提交活动表单
    submitActivityForm() {
      this.$refs.activityForm.validate(async (valid) => {
        if (valid) {
          try {
            // 模拟API调用
            setTimeout(() => {
              if (this.activityForm.id) {
                // 编辑现有活动
                const index = this.activityList.findIndex(item => item.id === this.activityForm.id);
                if (index !== -1) {
                  this.activityList[index] = { ...this.activityList[index], ...this.activityForm };
                }
                this.$message.success('编辑成功');
              } else {
                // 添加新活动
                const newActivity = {
                  ...this.activityForm,
                  id: Date.now(),
                  participants: 0,
                  startTime: this.formatDateTime(this.activityForm.startTime),
                  endTime: this.formatDateTime(this.activityForm.endTime)
                };
                this.activityList.unshift(newActivity);
                this.pagination.total += 1;
                this.$message.success('添加成功');
              }
              this.editDialogVisible = false;
            }, 500);
            
            // 实际API调用
            // const isEdit = !!this.activityForm.id;
            // const url = isEdit ? `/api/admin/activity/update/${this.activityForm.id}` : '/api/admin/activity/create';
            // const method = isEdit ? 'put' : 'post';
            // const response = await httpInstance[method](url, this.activityForm);
            // 
            // if (response && response.code === 200) {
            //   this.$message.success(isEdit ? '编辑成功' : '添加成功');
            //   this.editDialogVisible = false;
            //   this.fetchActivityList();
            // } else {
            //   this.$message.error(response?.msg || (isEdit ? '编辑失败' : '添加失败'));
            // }
          } catch (error) {
            console.error(this.activityForm.id ? '编辑活动失败:' : '添加活动失败:', error);
            this.$message.error(this.activityForm.id ? '编辑失败，请稍后重试' : '添加失败，请稍后重试');
          }
        } else {
          return false;
        }
      });
    },
    
    // 取消活动
    cancelActivity(activity) {
      this.$confirm(`确定要撤销"${activity.title || activity.name}"活动吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          this.loading = true;
          
          // 调用撤销活动的API
          const response = await httpInstance.post('/api/activity/approve', {
            status: 2,  // 活动被撤销的状态
            activityId: activity.id
          });
          
          if (response && response.code === 200) {
            this.$message.success('活动已成功撤销');
            // 重新获取活动列表
            this.fetchActivityList();
          } else {
            this.$message.error(response?.msg || '撤销活动失败');
          }
        } catch (error) {
          console.error('撤销活动失败:', error);
          this.$message.error('撤销活动失败，请稍后重试');
        } finally {
          this.loading = false;
        }
      }).catch(() => {
        // 用户取消操作
        this.$message.info('已取消撤销操作');
      });
    },
    
    // 分页大小变化
    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.handleFrontendPagination();
    },
    
    // 当前页变化
    handleCurrentChange(page) {
      this.pagination.currentPage = page;
      this.handleFrontendPagination();
    },
    
    // 根据活动类型返回不同的标签类型
    getTagType(type) {
      type = type.trim();
      const typeMap = {
        '文化活动': 'success',
        '体育赛事': 'warning',
        '学术讲座': 'primary',
        '志愿服务': 'info',
        '招新活动': 'danger'
      };
      
      // 如果找不到精确匹配，尝试部分匹配
      if (typeMap[type]) {
        return typeMap[type];
      }
      
      // 部分匹配
      if (type.includes('文化') || type.includes('艺术')) return 'success';
      if (type.includes('体育') || type.includes('运动')) return 'warning';
      if (type.includes('学术') || type.includes('讲座') || type.includes('科技')) return 'primary';
      if (type.includes('志愿') || type.includes('公益') || type.includes('服务')) return 'info';
      if (type.includes('招新') || type.includes('招募')) return 'danger';
      
      // 默认返回
      return '';
    },
    
    // 根据状态返回不同的标签类型
    getStatusType(status) {
      const statusMap = {
        '未开始': 'info',
        '进行中': 'primary',
        '已结束': 'success',
        '已取消': 'danger'
      };
      return statusMap[status] || '';
    },
    
    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '未设置';
      
      try {
        const date = new Date(dateTime);
        if (isNaN(date.getTime())) return dateTime; // 如果解析失败，返回原始值
        
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        
        return `${year}-${month}-${day} ${hours}:${minutes}`;
      } catch (error) {
        console.error('日期格式化错误:', error);
        return dateTime; // 出错时返回原始值
      }
    },
    
    // 根据状态值返回不同的标签类型
    getStatusTypeByValue(status) {
      const statusMap = {
        0: 'warning',   // 待审批
        1: 'success',   // 审批通过
        2: 'danger'     // 活动被撤销
      };
      return statusMap[status] || '';
    },
    
    // 根据状态值返回状态文本
    getStatusTextByValue(status) {
      const statusMap = {
        0: '待审批',
        1: '已审核',
        2: '已撤销'
      };
      return statusMap[status] || '未知状态';
    },
    
    // 格式化日期（仅日期部分）
    formatDate(dateStr) {
      if (!dateStr) return '未设置';
      
      try {
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) return dateStr; // 如果解析失败，返回原始值
        
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        
        return `${year}-${month}-${day}`;
      } catch (error) {
        console.error('日期格式化错误:', error);
        return dateStr; // 出错时返回原始值
      }
    }
  }
}
</script>

<style scoped>
.activity-list {
  padding-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-operations {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-end;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.danger-button {
  color: #F56C6C;
}

.detail-section {
  margin-top: 30px;
}

.detail-section h3 {
  font-size: 16px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  color: #303133;
}

.activity-image-container {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}

.no-image {
  width: 100%;
  max-width: 500px;
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #909399;
}

.no-image i {
  font-size: 40px;
  margin-bottom: 10px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
}

.image-slot i {
  font-size: 30px;
}

/* 确保对话框内容可滚动 */
.el-dialog__body {
  max-height: 60vh;
  overflow-y: auto;
}
</style>
